package com.wlts.wzy.KSOrderModule.util;

import com.alibaba.fastjson.JSON;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.request.KsMerchantOrderListRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantRefundListRequest;
import com.kuaishou.merchant.open.api.response.KsMerchantOrderListResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantRefundListResponse;
import com.kuaishou.merchant.open.api.response.view.order.MerchantOrderInfoView;
import com.kuaishou.merchant.open.api.response.view.refund.MerchantRefundInfoView;
import com.wlts.wzy.Base.BaseEntity;
import com.wlts.wzy.KSGoodsModule.service.IKsCategoryService;
import com.wlts.wzy.KSOrderModule.entity.KsOrders;
import com.wlts.wzy.KSOrderModule.entity.KsOrdersRefund;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersRefundService;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersService;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 更新售后订单
 */
@Component
public class KsOrdersRefundUpdate {
    @Autowired
    private IKsOauthService ksOauthService;
    @Autowired
    private IKsOrdersRefundService ksOrdersRefundService;
    @Autowired
    private IKsOrdersService ksOrdersService;

    @Scheduled(fixedDelay = 117 * 1000)
    // @PostConstruct
    /**
     * 将快手售后订单更新到本地库
     */
    public void updateOrders() {

        MyLambdaQueryWrapper<KsOauth> ksOauthWrapper = new MyLambdaQueryWrapper<>();

        ksOauthWrapper.eq(KsOauth::getDelFlag, "0");
        ksOauthWrapper.ge(KsOauth::getTokenOverTime, LocalDateTime.now());
        ksOauthWrapper.eq(KsOauth::getTokenStatus, 0);
        List<KsOauth> oauthList = ksOauthService.list(ksOauthWrapper);

        oauthList.forEach(ksOauth -> {
            KsMerchantRefundListRequest orderListRequest = new KsMerchantRefundListRequest();
            orderListRequest.setAccessToken(ksOauth.getAccessToken());
            orderListRequest.setType(9);//退款单请求类型，8 等待退款 9 全部退款订单
            orderListRequest.setSort(1);//排序方式，1时间降序 2时间升序 ，默认降序
            orderListRequest.setQueryType(2);//查找方式，1按创建时间查找 2按更新时间查找 ，默认创建时间
            orderListRequest.setNegotiateStatus(1);

            long end = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

            int page = 1;
            String pcursor = null;

            while (true) {
                orderListRequest.setCurrentPage(page);
                orderListRequest.setPageSize(100);
                orderListRequest.setPcursor(pcursor);

                AccessTokenKsMerchantClient tokenKsMerchantClient
                        = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey, KsConfigInfo.signSecret);

                KsMerchantRefundListResponse response = null;
                try {
                    /**
                     * 默认查一天的订单
                     */
                    orderListRequest.setBeginTime(end - 86400000);

                    orderListRequest.setEndTime(end);

                    response = tokenKsMerchantClient.execute(orderListRequest);

                    if (response.getResult() == 200015) {
                        orderListRequest.setBeginTime(end - 3600000);
                        response = tokenKsMerchantClient.execute(orderListRequest);
                    }

                    if (response.getResult() == 200015) {
                        orderListRequest.setBeginTime(end - 60000);
                        response = tokenKsMerchantClient.execute(orderListRequest);
                    }

             //       System.out.println(JSON.toJSONString(response));

                    List<MerchantRefundInfoView> orderInfoViews = response.getMerchantRefundListData().getRefundOrderInfoList();

                    List<KsOrdersRefund> ksOrdersList = orderInfoViews.stream().map(a -> {

                        MyLambdaQueryWrapper<KsOrdersRefund> orderWrapper = new MyLambdaQueryWrapper<>();
                        orderWrapper.eq(KsOrdersRefund::getOid, a.getOid());
                        orderWrapper.eq(KsOrdersRefund::getDelFlag, "0");
                        KsOrdersRefund orders = ksOrdersRefundService.getOne(orderWrapper);

                        if (orders == null) {
                            orders = new KsOrdersRefund();
                            updateKsRefundStatus(a);
                        } else {
                            if (a.getStatus() != orders.getStatus()) {
                                updateKsRefundStatus(a);
                            }
                        }
                        CopyUtils.copyProperties(a, orders);
                        ksOrdersRefundService.saveOrUpdate(orders);

                        return orders;
                    }).collect(Collectors.toList());

//                    if (ksOrdersList.size() > 0) {
//
//                        ksOrdersRefundService.saveOrUpdateBatch(ksOrdersList);
//                    }
                    pcursor = response.getMerchantRefundListData().getPcursor();
                    if (pcursor.equals("nomore")) {
                        break;
                    }

                } catch (KsMerchantApiException e) {
                    e.printStackTrace();
                    break;
                }
            }
        });

    }

    private void updateKsRefundStatus(MerchantRefundInfoView a) {
        MyLambdaQueryWrapper<KsOrders> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.eq(KsOrders::getOid, a.getOid());

        wrapper.eq(BaseEntity::getDelFlag, "0");

        KsOrders ksOrders = ksOrdersService.getOne(wrapper);

        if (ksOrders != null) {
            ksOrders.setKsRefundId(a.getRefundId());
            ksOrders.setKsRefundStatus(a.getStatus());
            ksOrdersService.updateById(ksOrders);
        }
    }


}
